package com.heima.wemedia.filter;

import com.alibaba.fastjson.JSON;
import com.heima.wemedia.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@Order(0)
public class AuthorizationFilter implements GlobalFilter {

    private static List<String> urlList = new ArrayList<>();

    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");    //网关 API 文档路径
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断请求路径是否需要拦截
        String requestURL = request.getURI().getPath();
        for (String url : urlList) {
            //2.1不需要拦截，直接放行
            if(requestURL.contains(url)){
               return  chain.filter(exchange);
            }
        }
        //3.需要拦截，获取请求头中的 token 信息
        String token = request.getHeaders().getFirst("token");
        //3.1请求头中没有 token，终止请求，返回响应状态为 401
        if(StringUtils.isBlank(token)){
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //return response.setComplete();
            return writeMessage(exchange, "未携带 token");
        }
        //4.认证解析 token
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int statusCode = AppJwtUtil.verifyToken(claimsBody);
            if(statusCode < 1){
                //4.2解析成功，将登录用户的 id 设置到请求头中，放行请求
                Object id = claimsBody.get("id");
                request.mutate().header("userId", String.valueOf(id));
                exchange.mutate().request(request);
                log.info("网关解析 token 成功，当前登录用户的 id 为: {}", id);
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("网关解析 token 失败，异常原因: {}", e.getMessage());
        }
        //4.1解析失败，直接终止请求 [-1(有效)、0(有效)、1(过期)、2(过期)]
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //return response.setComplete();
        return writeMessage(exchange,"token 已过期，请重新登录");
    }

    /**
     * 返回错误提示信息
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
